import { defineStore } from 'pinia'
import { useSocketStore } from './socket'

// 课后托班管理store
export const useAfterSchoolStore = defineStore('afterSchool', {
  state: () => ({
    // 托班班级列表
    classes: [],
    // 托班学生列表
    students: [],
    // 当前选中的托班班级ID
    selectedClassId: null,
    // 当前选中的日期
    selectedDate: new Date().toISOString().split('T')[0],
    // 加载状态
    loading: false,
    // 错误信息
    error: null
  }),

  getters: {
    // 获取当前选中的托班班级
    selectedClass: (state) => {
      return state.classes.find(c => c.id === state.selectedClassId) || null
    },
    
    // 获取指定状态的学生
    getStudentsByStatus: (state) => (status) => {
      return state.students.filter(student => student.check_in_status === status)
    },
    
    // 获取已签到但未签退的学生
    checkedInStudents: (state) => {
      return state.students.filter(student => 
        student.check_in_status === 'checked_in'
      )
    },
    
    // 获取已签退的学生
    checkedOutStudents: (state) => {
      return state.students.filter(student => 
        student.check_in_status === 'checked_out'
      )
    }
  },

  actions: {
    // 初始化WebSocket监听
    initSocketListeners() {
      const socketStore = useSocketStore()
      
      // 监听课后托班班级数据
      socketStore.on('after-school-classes-data', this.handleClassesData)
      
      // 监听课后托班学生数据
      socketStore.on('after-school-students-data', this.handleStudentsData)
      
      // 监听学生签到结果
      socketStore.on('after-school-check-in-result', this.handleCheckInResult)
      
      // 监听学生签退结果
      socketStore.on('after-school-check-out-result', this.handleCheckOutResult)
      
      // 监听课后托班相关更新
      socketStore.on('after-school-updated', (data) => {
        this.handleAfterSchoolUpdate(data)
      })
      
      // 监听学生状态更新
      socketStore.on('student-status-updated', (data) => {
        this.handleStudentStatusUpdate(data)
      })
    },
    
    // 获取托班班级列表 - 使用WebSocket
    fetchClasses() {
      const socketStore = useSocketStore()
      this.loading = true
      this.error = null
      socketStore.emit('get-after-school-classes')
    },
    
    // 获取托班学生列表 - 使用WebSocket
    fetchStudents(params = {}) {
      const socketStore = useSocketStore()
      this.loading = true
      this.error = null
      
      // 合并查询参数
      const queryParams = {
        date: this.selectedDate,
        ...params
      }
      
      if (this.selectedClassId) {
        queryParams.class_id = this.selectedClassId
      }
      
      socketStore.emit('get-after-school-students', queryParams)
    },
    
    // 学生进入托班 - 使用WebSocket
    checkInStudent(data) {
      const socketStore = useSocketStore()
      this.loading = true
      this.error = null
      socketStore.emit('after-school-check-in', data)
    },
    
    // 学生离开托班 - 使用WebSocket
    checkOutStudent(data) {
      const socketStore = useSocketStore()
      this.loading = true
      this.error = null
      socketStore.emit('after-school-check-out', data)
    },
    
    // 处理托班班级数据
    handleClassesData(data) {
      console.log('收到托班班级数据:', data)
      this.loading = false
      if (data.success) {
        this.classes = data.classes || []
      } else {
        this.error = data.message || '获取托班班级列表失败'
      }
    },
    
    // 处理托班学生数据
    handleStudentsData(data) {
      console.log('收到托班学生数据:', data)
      this.loading = false
      if (data.success) {
        this.students = data.students || []
      } else {
        this.error = data.message || '获取托班学生列表失败'
      }
    },
    
    // 处理学生签到结果
    handleCheckInResult(data) {
      console.log('收到学生签到结果:', data)
      this.loading = false
      if (data.success) {
        // 更新本地学生状态
        this.updateStudentStatus(data.student_id, {
          check_in_status: 'checked_in',
          after_school_class_id: data.after_school_class_id,
          check_in_time: new Date().toISOString(),
          notes: data.notes || ''
        })
      } else {
        this.error = data.message || '学生进入托班失败'
      }
    },
    
    // 处理学生签退结果
    handleCheckOutResult(data) {
      console.log('收到学生签退结果:', data)
      this.loading = false
      if (data.success) {
        // 更新本地学生状态
        this.updateStudentStatus(data.student_id, {
          check_in_status: 'checked_out',
          check_out_time: new Date().toISOString(),
          notes: data.notes || ''
        })
      } else {
        this.error = data.message || '学生离开托班失败'
      }
    },
    
    // 更新学生状态（本地）
    updateStudentStatus(studentId, statusData) {
      const studentIndex = this.students.findIndex(s => s.student_id === studentId)
      if (studentIndex !== -1) {
        this.students[studentIndex] = {
          ...this.students[studentIndex],
          ...statusData
        }
      }
    },
    
    // 设置选中的托班班级
    setSelectedClass(classId) {
      this.selectedClassId = classId
      // 重新获取该班级的学生
      if (classId) {
        this.fetchStudents({ class_id: classId })
        // 加入课后托班WebSocket房间
        const socketStore = useSocketStore()
        socketStore.emit('join-after-school-room', { classId })
      }
    },
    
    // 设置选中日期
    setSelectedDate(date) {
      this.selectedDate = date
      // 重新获取该日期的数据
      this.fetchStudents({ date })
    },
    
    // 处理WebSocket学生状态更新
    handleStudentStatusUpdate(data) {
      // 如果是课后托班相关的状态更新，更新本地学生状态
      if (data.update_type === 'after_school_check_in' || 
          data.update_type === 'after_school_check_out') {
        
        const studentIndex = this.students.findIndex(s => s.student_id === data.student_id)
        
        if (studentIndex !== -1) {
          // 更新现有学生
          this.students[studentIndex] = {
            ...this.students[studentIndex],
            check_in_status: data.update_type === 'after_school_check_in' ? 'checked_in' : 'checked_out',
            check_in_time: data.update_type === 'after_school_check_in' ? data.timestamp : this.students[studentIndex].check_in_time,
            check_out_time: data.update_type === 'after_school_check_out' ? data.timestamp : this.students[studentIndex].check_out_time,
            notes: data.notes || this.students[studentIndex].notes
          }
        } else if (data.update_type === 'after_school_check_in' && 
                  (!this.selectedClassId || this.selectedClassId === data.after_school_class_id)) {
          // 如果是新学生进入托班，且当前选中的班级匹配或未选择班级，则添加到列表
          this.fetchStudents()
        }
      }
    },
    
    // 处理WebSocket课后托班更新
    handleAfterSchoolUpdate(data) {
      // 根据更新类型处理
      if (data.operation === 'check_in') {
        // 学生进入托班
        const studentIndex = this.students.findIndex(s => s.student_id === data.student_id)
        
        if (studentIndex !== -1) {
          // 更新现有学生
          this.students[studentIndex] = {
            ...this.students[studentIndex],
            check_in_status: 'checked_in',
            after_school_class_id: data.after_school_class_id,
            check_in_time: data.timestamp,
            notes: data.notes || this.students[studentIndex].notes
          }
        } else if (!this.selectedClassId || this.selectedClassId === data.after_school_class_id) {
          // 如果是新学生进入托班，且当前选中的班级匹配或未选择班级，则添加到列表
          this.fetchStudents()
        }
      } else if (data.operation === 'check_out') {
        // 学生离开托班
        const studentIndex = this.students.findIndex(s => s.student_id === data.student_id)
        
        if (studentIndex !== -1) {
          // 更新现有学生
          this.students[studentIndex] = {
            ...this.students[studentIndex],
            check_in_status: 'checked_out',
            check_out_time: data.timestamp,
            notes: data.notes || this.students[studentIndex].notes
          }
        }
      }
    },
    
    // 处理定期状态更新
    handlePeriodicUpdate(studentsData) {
      try {
        if (!studentsData || !Array.isArray(studentsData)) {
          return
        }
        
        // 更新托班学生状态数据
        studentsData.forEach(updatedStudent => {
          const existingIndex = this.students.findIndex(s => s.student_id === updatedStudent.student_id)
          if (existingIndex !== -1) {
            // 更新现有学生的状态
            this.students[existingIndex] = {
              ...this.students[existingIndex],
              arrival_status: updatedStudent.arrival_status,
              departure_status: updatedStudent.departure_status,
              check_in_status: updatedStudent.check_in_status || this.students[existingIndex].check_in_status,
              notes: updatedStudent.notes,
              updated_at: updatedStudent.updated_at
            }
          }
        })
        
        console.log('📊 托班学生状态已通过定期更新同步')
      } catch (error) {
        console.error('处理托班定期状态更新失败:', error)
      }
    },
    
    // 重置store状态
    resetStore() {
      this.classes = []
      this.students = []
      this.selectedClassId = null
      this.selectedDate = new Date().toISOString().split('T')[0]
      this.loading = false
      this.error = null
    }
  }
})